/*
 * @Author: your name
 * @Date: 2024-04-19 09:13:43
 * @LastEditTime: 2024-04-19 09:35:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\116.填充每个节点的下一个右侧节点指针.cpp
 */
/*
 * @lc app=leetcode.cn id=116 lang=cpp
 *
 * [116] 填充每个节点的下一个右侧节点指针
 */

// @lc code=start
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        if(root == nullptr){
            return nullptr;
        }
        queue<Node*> que;
        que.push(root);
        while(!que.empty()){
            int size = que.size();

            for(int i = 0; i < size; i++){
                Node* tmp_node = que.front();
                // cout<<tmp_node->val<<endl;
                que.pop();
                // 先把左右孩子加进队列
                if(tmp_node->left) que.push(tmp_node->left);
                if(tmp_node->right) que.push(tmp_node->right);
                // 判断是否是该层最后一个
                if(i == size -1){
                    break;
                }
                tmp_node->next = que.front();
                
            }
        }
        return root;
    }
};
// @lc code=end

